﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using POSSystem.BLL;
using MyGeneration.dOOdads;

namespace WebUI.EditPages
{
    public partial class ProblemList : BasePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            base.Page_Load(sender, e);
            if (!IsPostBack)
                ReloadList();

            btnAdd.Enabled = Branches.CurrentBranchID == SessionUser.BranchID && SessionUser.Admin;
            btnDelete.Enabled = Branches.CurrentBranchID == SessionUser.BranchID && SessionUser.Admin;
            btnDeleteCat.Enabled = Branches.CurrentBranchID == SessionUser.BranchID && SessionUser.Admin;
            btnAddCat.Enabled = Branches.CurrentBranchID == SessionUser.BranchID && SessionUser.Admin;

            if (Branches.CurrentBranchID != SessionUser.BranchID || !SessionUser.Admin)
            {
                btnAdd.OnClientClick = "";
                btnDelete.OnClientClick = "";
                btnDeleteCat.OnClientClick = "";
                btnAddCat.OnClientClick = "";
            }
        }

        public string ProblemsKey
        {
            get
            {
                if (ViewState["RepairModelsKey"] == null)
                    ViewState["RepairModelsKey"] = Guid.NewGuid().ToString();
                return ViewState["RepairModelsKey"].ToString();
            }
        }

        public Problems RepairProblemList
        {
            get { return Session[ProblemsKey] == null ? null : (Problems)Session[ProblemsKey]; }
            set { Session[ProblemsKey] = value; }
        }

        public string ProblemCategoriesKey
        {
            get
            {
                if (ViewState["ProblemCategoriesKey"] == null)
                    ViewState["ProblemCategoriesKey"] = Guid.NewGuid().ToString();
                return ViewState["ProblemCategoriesKey"].ToString();
            }
        }

        public ProblemCategories ProblemCategoryList
        {
            get { return Session[ProblemCategoriesKey] == null ? null : (ProblemCategories)Session[ProblemCategoriesKey]; }
            set { Session[ProblemCategoriesKey] = value; }
        }

        private void ReloadList()
        {
            RepairProblemList = Problems.GetAllActiveProblems();
            Utilities.LoadListbox(lstProblems, RepairProblemList.DefaultView, Problems.ColumnNames.Description, Problems.ColumnNames.ID);

            ProblemCategoryList = ProblemCategories.GetAllActiveCategories();
            Utilities.LoadListbox(lstCategory, ProblemCategoryList.DefaultView, ProblemCategories.ColumnNames.ProblemCategoryName, ProblemCategories.ColumnNames.ID);
        }

        private void RefreshList()
        {
            if (hidSelectedID.Value != "")
            {
                lstCategory.SelectedIndex = 0;
                RepairProblemList.Filter = RepairModels.ColumnNames.Deleted + " = 0 and " + Problems.ColumnNames.CategoryID + " = " + hidSelectedID.Value;
                Utilities.LoadListbox(lstProblems, RepairProblemList.DefaultView, Problems.ColumnNames.Description, Problems.ColumnNames.ID);
            }
            else
                lstProblems.Items.Clear();
        }

        private void RefreshCatList()
        {

            ProblemCategoryList.Filter = ProblemCategories.ColumnNames.Deleted + " = 0";
            Utilities.LoadListbox(lstCategory, ProblemCategoryList.DefaultView, ProblemCategories.ColumnNames.ProblemCategoryName, ProblemCategories.ColumnNames.ID);
        }

        protected void btnDelete_OnClick(object sender, EventArgs e)
        {
            try
            {
                for (int i = lstProblems.Items.Count - 1; i >= 0; i--)
                {
                    if (lstProblems.Items[i].Selected)
                    {
                        RepairProblemList.Filter = RepairModels.ColumnNames.ID + "=" + lstProblems.Items[i].Value;
                        if (RepairProblemList.RowCount > 0)
                        {
                            RepairProblemList.Deleted = true;
                            RepairProblemList.LastModifiedByUser = SessionUser.ID;
                            RepairProblemList.LastModifiedDate = DateTime.UtcNow.AddHours(SysVars.TimeZone);
                        }
                    }
                }

                RepairProblemList.Save();
                RefreshList();
            }
            catch (Exception ex)
            {
                ErrorLog.WriteToFile("ProblemList.cs", "btnDelete_OnClick", ex.StackTrace);
                ((Popup)Master).ShowErrorMessage("Error:" + ex.Message);
            }
        }

        protected void btnLoad_OnClick(object sender, EventArgs e)
        {
            RefreshList();
        }


        protected void btnAdd_OnClick(object sender, EventArgs e)
        {
            if (hidSelectedID.Value == "")
            {
                ((Popup)Master).ShowErrorMessage("Select a category!");
                return;
            }

            TransactionMgr tx = TransactionMgr.ThreadTransactionMgr();
            try
            {
                tx.BeginTransaction();

                if (RepairProblemList == null)
                    ReloadList();

                RepairProblemList.AddNew();
                RepairProblemList.BranchID = Branches.CurrentBranchID;
                RepairProblemList.Description = txtName.Text;
                RepairProblemList.Deleted = false;
                RepairProblemList.LastModifiedByUser = SessionUser.ID;
                RepairProblemList.s_CategoryID = hidSelectedID.Value;
                RepairProblemList.LastModifiedDate = DateTime.UtcNow.AddHours(SysVars.TimeZone);
                RepairProblemList.Save();

                RepairModels models = RepairModels.GetAllActiveModels();
                RepairModelProblems modelProbs = new RepairModelProblems();
                for (int i = 0; i < models.RowCount; i++)
                {
                    modelProbs.AddNew();
                    modelProbs.BranchID = Branches.CurrentBranchID;
                    modelProbs.RepairModelID = models.ID;
                    modelProbs.ProblemID = RepairProblemList.ID;
                    modelProbs.RPP = 0;
                    modelProbs.StandardPrice = 0;
                    modelProbs.SpecialPrice = 0;

                    models.MoveNext();
                }

                modelProbs.Save();

                tx.CommitTransaction();

                RefreshList();
            }
            catch (Exception ex)
            {
                tx.RollbackTransaction();
                ErrorLog.WriteToFile("ProblemList.cs", "btnAdd_OnClick", ex.StackTrace);
                ((Popup)Master).ShowErrorMessage("Error:" + ex.Message);
            }
        }

        protected void btnAddCat_OnClick(object sender, EventArgs e)
        {
            try
            {
                ProblemCategoryList.AddNew();
                ProblemCategoryList.BranchID = Branches.CurrentBranchID;
                ProblemCategoryList.Deleted = false;
                ProblemCategoryList.ProblemCategoryName = txtCatName.Text;
                ProblemCategoryList.LastModifiedByUser = SessionUser.ID;
                ProblemCategoryList.LastModifiedDate = DateTime.UtcNow.AddHours(SysVars.TimeZone);
                ProblemCategoryList.Save();

                RefreshCatList();
            }
            catch (Exception ex)
            {
                ErrorLog.WriteToFile("ProblemList.cs", "btnAddCat_OnClick", ex.StackTrace);
                ((Popup)Master).ShowErrorMessage("Error:" + ex.Message);
            }
        }

        protected void btnDeleteCat_OnClick(object sender, EventArgs e)
        {
            try
            {
                for (int i = lstCategory.Items.Count - 1; i >= 0; i--)
                {
                    if (lstCategory.Items[i].Selected)
                    {
                        ProblemCategoryList.Filter = RepairModels.ColumnNames.ID + "=" + lstCategory.Items[i].Value;
                        if (ProblemCategoryList.RowCount > 0)
                        {
                            string oldFilter = RepairProblemList.Filter;
                            RepairProblemList.Filter = Problems.ColumnNames.CategoryID + " = " + ProblemCategoryList.s_ID;
                            RepairProblemList.Rewind();
                            while(!RepairProblemList.EOF)
                            {
                                RepairProblemList.Deleted = true;
                                RepairProblemList.LastModifiedByUser = SessionUser.ID;
                                RepairProblemList.LastModifiedDate = DateTime.UtcNow.AddHours(SysVars.TimeZone);
                                RepairProblemList.MoveNext();
                            }
                            ProblemCategoryList.Deleted = true;
                            ProblemCategoryList.LastModifiedByUser = SessionUser.ID;
                            ProblemCategoryList.LastModifiedDate = DateTime.UtcNow.AddHours(SysVars.TimeZone);
                            RepairProblemList.Filter = oldFilter;
                        }
                    }
                }

                ProblemCategoryList.Save();
                RepairProblemList.Save();
                RefreshCatList();
                RefreshList();
            }
            catch (Exception ex)
            {
                ErrorLog.WriteToFile("ProblemList.cs", "btnDeleteCat_OnClick", ex.StackTrace);
                ((Popup)Master).ShowErrorMessage("Error:" + ex.Message);
            }
        }
    }
}